package com.task.service;

import com.task.common.entity.sys.model.LoginUser;
import com.task.common.entity.sys.Permission;
import com.task.common.entity.sys.Role;
import com.task.common.entity.sys.SysUser;
import com.task.common.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Huzz
 * @created 2021-11-12 17:44
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private IUserService userService;

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IRoleService roleService;

    /**
     * 创建Security的User对象并返回
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null || "".equals(username)) {
            throw new ServiceException("用户不能为空");
        }
        SysUser sysUser = userService.findUserByUsername(username);
        if (sysUser == null) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("用户不存在");
        }
        if (sysUser.getStatus() == 0) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        /** 查询权限 */
        Set<String> authorityList = new HashSet<>();
        if (sysUser.isAdmin()) {
            authorityList.add("*:*:*");
        }
        Set<Integer> roleIds = new HashSet<>();
        List<Role> roleList = roleService.getLoginUserRoleByUserId(sysUser.getId());
        sysUser.setRoleList(roleList);
        roleList.forEach(role -> roleIds.add(role.getId()));
        List<Permission> permissionList = permissionService.getLoginUserPermissionByRoleId(roleIds);
        permissionList.forEach(permission -> authorityList.add(permission.getPerm()));
        /**
         * == User的构造函数 ==
         * String username：用户名
         * String password： 密码
         * boolean enabled： 账号是否可用
         * boolean accountNonExpired：账号是否过期
         * boolean credentialsNonExpired：密码是否过期
         * boolean accountNonLocked：账号是否锁定
         * Collection<? extends GrantedAuthority> authorities)：用户权限列表
         */
        return new LoginUser(sysUser.getId(), sysUser, authorityList);
    }
}
